from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from .models import Project, Group, Satellite
from .serializers import (
    ProjectSerializer, 
    GroupSerializer, 
    SatelliteSerializer,
    ProjectCreateUpdateSerializer,
    GroupCreateUpdateSerializer,
    SatelliteCreateUpdateSerializer
)


class ProjectViewSet(viewsets.ModelViewSet):
    """
    项目视图集
    """
    queryset = Project.objects.all().prefetch_related('groups__satellites').order_by('id')
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    ordering = ['id']
    ordering_fields = ['id', 'created_at', 'name']
    pagination_class = None  # 禁用分页
    
    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return ProjectCreateUpdateSerializer
        return ProjectSerializer
    
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'success': True,
            'data': serializer.data,
            'message': '项目列表获取成功'
        })
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            project = serializer.save()
            return Response({
                'success': True,
                'data': ProjectSerializer(project).data,
                'message': '项目创建成功'
            }, status=status.HTTP_201_CREATED)
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': '项目创建失败'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            project = serializer.save()
            return Response({
                'success': True,
                'data': ProjectSerializer(project).data,
                'message': '项目更新成功'
            })
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': '项目更新失败'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return Response({
            'success': True,
            'message': '项目删除成功'
        }, status=status.HTTP_204_NO_CONTENT)


class GroupViewSet(viewsets.ModelViewSet):
    """
    组视图集
    """
    queryset = Group.objects.all().select_related('project').prefetch_related('satellites').order_by('id')
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['project']
    ordering = ['id']
    ordering_fields = ['id', 'created_at', 'name']
    pagination_class = None  # 禁用分页
    
    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return GroupCreateUpdateSerializer
        return GroupSerializer
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            group = serializer.save()
            return Response({
                'success': True,
                'data': GroupSerializer(group).data,
                'message': '组创建成功'
            }, status=status.HTTP_201_CREATED)
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': '组创建失败'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            group = serializer.save()
            return Response({
                'success': True,
                'data': GroupSerializer(group).data,
                'message': '组更新成功'
            })
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': '组更新失败'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return Response({
            'success': True,
            'message': '组删除成功'
        }, status=status.HTTP_204_NO_CONTENT)


class SatelliteViewSet(viewsets.ModelViewSet):
    """
    卫星视图集
    """
    queryset = Satellite.objects.all().select_related('group__project').order_by('id')
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['group', 'group__project']
    ordering = ['id']
    ordering_fields = ['id', 'created_at', 'name']
    pagination_class = None  # 禁用分页
    
    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return SatelliteCreateUpdateSerializer
        return SatelliteSerializer
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            satellite = serializer.save()
            return Response({
                'success': True,
                'data': SatelliteSerializer(satellite).data,
                'message': '卫星创建成功'
            }, status=status.HTTP_201_CREATED)
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': '卫星创建失败'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            satellite = serializer.save()
            return Response({
                'success': True,
                'data': SatelliteSerializer(satellite).data,
                'message': '卫星更新成功'
            })
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': '卫星更新失败'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return Response({
            'success': True,
            'message': '卫星删除成功'
        }, status=status.HTTP_204_NO_CONTENT)